package zhh.tangbao.commodity.serivce.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhh.tangbao.commodity.constant.OrderStatus;
import zhh.tangbao.commodity.constant.PickupStatus;
import zhh.tangbao.commodity.dao.CommodityOrderContentDao;
import zhh.tangbao.commodity.dao.CommodityOrderDao;
import zhh.tangbao.commodity.dto.CommodityOrderQueryDto;
import zhh.tangbao.commodity.entity.CommodityOrder;
import zhh.tangbao.commodity.entity.CommodityOrderContent;
import zhh.tangbao.commodity.serivce.CommodityOrderService;
import zhh.tangbao.commodity.vo.OrderInfoVo;
import zhh.tangbao.system.constant.DataStatus;
import zhh.tangbao.system.utils.UserHolderUtil;
import zhh.tangbao.system.vo.SelectOptionsVo;
import zhh.tangbao.wechat.dao.WeChatUserDao;
import zhh.tangbao.wechat.entity.WeChatUser;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 描述
 * </p>
 *
 * @author 粥灰灰
 * <p>2023/3/4</p>
 */

@Service
public class CommodityOrderServiceImpl implements CommodityOrderService {

    @Autowired
    private CommodityOrderDao dao;

    @Autowired
    private CommodityOrderContentDao contentDao;

    @Autowired
    private UserHolderUtil userHolderUtil;

    @Autowired
    private WeChatUserDao weChatUserDao;

    @Override
    public OrderInfoVo get(String id) {
        CommodityOrder order = dao.selectOne(new QueryWrapper<CommodityOrder>().eq("id", id).eq("data_status", DataStatus.ENABLE));
        Assert.notNull(order, "该订单不存在或已被删除");
        order.setContent(getContent(order.getId()));
        OrderInfoVo vo = new OrderInfoVo(order);
        WeChatUser weChatUser = weChatUserDao.selectOne(new QueryWrapper<WeChatUser>().eq("id", order.getCreateUserId()));
        if (null != weChatUser) {
            vo.setCreateUserAccount(weChatUser.getPhoneNumber());
        }
        return vo;
    }

    @Override
    public Page<CommodityOrder> page(CommodityOrderQueryDto dto) {
        Page<CommodityOrder> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        QueryWrapper<CommodityOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("data_status", DataStatus.ENABLE).orderByDesc("record_time");
        // 根据订单编号指定搜索
        if (StrUtil.isNotBlank(dto.getId())) {
            wrapper.eq("id", dto.getId());
        }
        if (null != dto.getStart() && null != dto.getEnd()) {
            wrapper.between("record_time", dto.getStart(), dto.getEnd());
        }
        if (null != dto.getPaymentStart() && null != dto.getPaymentEnd()) {
            wrapper.between("payment_time", dto.getPaymentStart(), dto.getPaymentEnd());
        }
        if (CollUtil.isNotEmpty(dto.getOrderStatus())) {
            wrapper.in("order_status", dto.getOrderStatus());
        }
        // 是否需要通过电话号码查找
        if (StrUtil.isNotBlank(dto.getPhoneNumber())) {
            QueryWrapper<WeChatUser> weChatUserQueryWrapper = new QueryWrapper<>();
            weChatUserQueryWrapper.eq("phone_number", dto.getPhoneNumber());
            // 通过以上其一获取微信小程序的用户ID
            WeChatUser weChatUser = weChatUserDao.selectOne(weChatUserQueryWrapper);
            if (null != weChatUser) {
                wrapper.eq("create_user_id", weChatUser.getId());
            }
        }
        return dao.selectPage(page, wrapper);
    }

    @Transactional
    @Override
    public int add(CommodityOrder order) {
        order.setBaseCreateInfo(userHolderUtil.getCurrentUser().getId());
        int r = dao.insert(order);
        List<CommodityOrderContent> content = order.getContent();
        if (CollUtil.isEmpty(content)) {
            return r;
        }

        for (int i = 0; i < content.size(); i++) {
            CommodityOrderContent orderContent = content.get(i);
            orderContent.setCommodityOrderId(order.getId());
            if (OrderStatus.PICKED.getCode().equals(order.getOrderStatus())) {
                orderContent.setPickupStatus(PickupStatus.PICKED);
            }
        }
        contentDao.insertBatchSomeColumn(content);
        return r;
    }

    @Override
    public int delete(String id) {
        CommodityOrder order = dao.selectById(id);
        Assert.notNull(order, "该订单记录不存在或已被删除");
        order.setDataStatus(DataStatus.DELETED).setUpdateInfo(userHolderUtil.getCurrentUser().getId());
        return dao.updateById(order);
    }

    @Override
    public int update(CommodityOrder order) {
        order.setUpdateInfo(userHolderUtil.getCurrentUser().getId());
        return dao.updateById(order);
    }

    @Override
    public List<CommodityOrderContent> getContent(String orderId) {
        return contentDao.selectList(new QueryWrapper<CommodityOrderContent>().eq("commodity_order_id", orderId));
    }

    @Override
    public List<SelectOptionsVo> currentAllOrderStatusOptions() {
        Map<Integer, String> statusMap = OrderStatus.getOrderStatusMap();
        List<SelectOptionsVo> options = dao.getOrderStatusGroupByOrderStatus();
        if (CollUtil.isEmpty(options)) {
            return Lists.newArrayList();
        }
        for (int i = 0; i < options.size(); i++) {
            SelectOptionsVo vo = options.get(i);
            vo.setLabel(statusMap.get(vo.getIntegerKey()));
        }
        return options;
    }

    @Override
    public List<SelectOptionsVo> allOrderStatusOptions() {
        Map<Integer, String> map = OrderStatus.getOrderStatusMap();
        List<SelectOptionsVo> result = Lists.newArrayList();
        if (CollUtil.isEmpty(map)) {
            return result;
        }
        map.forEach((key, value) -> {
            result.add(new SelectOptionsVo(value, key));
        });
        return result;
    }

    @Override
    public int batchDelete(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return 0;
        }
        CommodityOrder update = new CommodityOrder();
        update.setBaseCreateInfo(userHolderUtil.getCurrentUser().getId(), new Date(), DataStatus.DELETED);
        contentDao.delete(new QueryWrapper<CommodityOrderContent>().in("commodity_order_id", ids));
        return dao.update(update, new QueryWrapper<CommodityOrder>().in("id", ids));
    }

    @Override
    public List<CommodityOrder> allOrderDuring(Date start, Date end, OrderStatus status) {
        return dao.selectList(new QueryWrapper<CommodityOrder>().between("record_time", start, end).eq("order_status", status.getCode()).eq("data_status", DataStatus.ENABLE));
    }

    @Override
    public List<CommodityOrderContent> batchSelectContentByOrderIds(Collection<String> orderIds) {
        return contentDao.selectList(new QueryWrapper<CommodityOrderContent>().in("commodity_order_id", orderIds));
    }

}
